/**
 * TODO vconsole开关控制
 * 1. 非生产环境都会默认打开vconsole
 * 2. 生产环境下，长按webview上方区域50px之内10s以上即可开启vconsole开关
 * 3. 生产环境下，开关开启后所有窗口在5分钟之内都会开启vconsole
 */
import storage from 'utils/helper/storage'
import ENV from 'utils/env'


class HiddenEgg {
  constructor (selector, callback) {
    // 查找文档中是否有指定选择器
    this.el = document && document.querySelector(selector)
    // console.log('this.el', this.el)
    if (!this.el) return

    // 点击次数计数
    this.clickCount = 0
    // 点击多少次可以触发
    this.trashold = 10

    this.callback = callback || function () {}

    this.clickHandler = this.clickHandler.bind(this)

    this.start()
  }

  start () {
    this.el.addEventListener('click', this.clickHandler, false)
  }

  clickHandler (evt) {
    // alert(evt.target)
    // console.log('evt.target', evt.target)
    if (evt.target !== this.el)  return

    this.clickCount++

    if (this.clickCount >= this.trashold) {
      this.callback()
    }
  }

  destroy () {
    this.el.removeEventListener('click', this.clickHandler, false)
  }
}

// 同一个会话是否已开启
function isVconsoleOpen () {
  let isOpen = false
  let vconsole = storage.get('__vconsole__', true)
  if (vconsole) {
    isOpen = true
  } else {
    storage.remove('__vconsole__')
  }
  return isOpen
}


function listenVconsole() {
  // 点击头部
  let crazyClick = new HiddenEgg('.uni-nav-bar-text span', function() {
    // 5分钟的过期时间
    storage.set('__vconsole__', 1, 300000)
    loadVconsole()
    crazyClick.destroy()
  })
}

function loadVconsole () {
  require.ensure([], r => {
    let VConsole = require('vconsole')
    let vc = new VConsole()
    loaded = true
  }, 'vconsole')
}

var loaded = false

export default function (router) {
  if (ENV !== 'production' || isVconsoleOpen()) { // 非生产环境或者已标记为开启 则，直接加载vconsole
    loadVconsole()
  } else {
    if (loaded) return

    // 假设1s内触发器渲染出来
    setTimeout(() => {
      listenVconsole()
    }, 1000)
  }
}
